{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Merge List Of Number Into Ranges\n",
    "\n",
    "[原题](https://mp.weixin.qq.com/s/0YPcU4vvke2LnT_vjS1Z_g)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Question\n",
    "\n",
    "Given a sorted list of numbers, return a list of strings that represent all of the consecutive numbers.\n",
    "\n",
    "```text\n",
    "Input: [0, 1, 2, 5, 7, 8, 9, 9, 10, 11, 15]\n",
    "Output: ['0->2', '5->5', '7->11', '15->15']\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "def findRanges(nums):\n",
    "    ''' Main Algorithm '''\n",
    "    \n",
    "    # Initialize a list.\n",
    "    # Every element in the list is also a list,\n",
    "    # representing the begin and the end of a range.\n",
    "    result = []\n",
    "    \n",
    "    # Scan all elements in the given list.\n",
    "    for elem in nums:\n",
    "        # The given list has been sorted before,\n",
    "        # so we just judge if it's consecutive.\n",
    "        if result != [] and elem <= (result[-1][-1] + 1):\n",
    "            # Update the end element of the last range.\n",
    "            result[-1][-1] = elem\n",
    "        else:\n",
    "            # Append a new range.\n",
    "            result.append([elem, elem])\n",
    "    \n",
    "    # Output prettify.\n",
    "    return [(str(start) + '->' + str(end)) for (start, end) in result]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['0->2', '5->5', '7->11', '15->15']\n"
     ]
    }
   ],
   "source": [
    "''' Test Scripts '''\n",
    "print(findRanges([0, 1, 2, 5, 7, 8, 9, 9, 10, 11, 15]))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.4"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
